import {
  WebSocketGateway,
  WebSocketServer,
  SubscribeMessage,
  OnGatewayConnection,
  OnGatewayDisconnect,
} from '@nestjs/websockets';
import { Server, Socket } from 'socket.io';

@WebSocketGateway({ namespace: 'auth' })
export class SocketGateway implements OnGatewayConnection, OnGatewayDisconnect {
  @WebSocketServer() server: Server;
  private sceneRoomMap = new Map<string, string>();

  handleConnection(client: Socket) {
    // 连接时等待客户端发送sceneStr注册
    console.log('Client connected:', client.id);
    // 添加心跳检测
    client.on('ping', () => client.emit('pong'));
  }

  handleDisconnect(client: Socket) {
    // 断开时清理相关房间（Map 的 forEach 回调参数顺序是 (value,key)）
    this.sceneRoomMap.forEach((clientId, sceneStr) => {
      if (clientId === client.id) {
        client.leave(sceneStr);
        this.sceneRoomMap.delete(sceneStr);
      }
    });
  }
  @SubscribeMessage('join')
  handleJoinRoom(client: Socket, sceneStr: string) {
    // 使用标准房间管理
    client.join(sceneStr);
    this.sceneRoomMap.set(sceneStr, client.id);
    // 添加超时自动清理
    setTimeout(() => {
      client.leave(sceneStr);
      this.sceneRoomMap.delete(sceneStr);
    }, 1800000);
  }

  // 新增状态更新通知方法
  public notifyStatusUpdate(sceneStr: string, statusInfo: { status: string; userInfo?: unknown }) {
    try {
      this.server.to(sceneStr).emit('statusUpdate', statusInfo); // 发送状态更新事件到指定场景房间

      // 通知后自动清理房间
      this.server.in(sceneStr).socketsLeave(sceneStr); // 从房间中移除所有客户端
      this.sceneRoomMap.delete(sceneStr);
    } catch (error) {
      console.error('WebSocket通知失败:', error);
    }
  }
}
